//
//  DFStatusPictureView.swift
//  FlyBlog
//
//  Created by FEI on 16/4/15.
//  Copyright © 2016年 FEI. All rights reserved.
//

import UIKit
import SDWebImage


private let DFStatusPictureViewCellMargin: CGFloat = 4

private let DFStatusPictureViewMaxColumn = 3

private let DFStatusPictureViewItemWH = (UIScreen.mainScreen().bounds.width - 2 * DFStatusCellMargin - (CGFloat(DFStatusPictureViewMaxColumn) - 1) * DFStatusPictureViewCellMargin) / CGFloat(DFStatusPictureViewMaxColumn)

class DFStatusPictureView: UICollectionView {
    private let ReuseIdentifier = "ReuseIdentifier"

    //配图的NSURL数组
    var pictureURLs: [NSURL]? {
        didSet {
            let size = calcViewSize()
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
            DFPrint("配图大小\(size)")
            self.reloadData()
        }
    }

    //计算配图宽高
    private func calcViewSize() -> CGSize {
      layout.itemSize = CGSize(width: DFStatusPictureViewItemWH, height: DFStatusPictureViewItemWH)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0

        //图片数量
        let count = pictureURLs?.count ?? 0

        if count == 0 {
            return CGSizeZero
        }

        if count == 1 {
            var size = CGSize(width: DFStatusPictureViewItemWH, height: DFStatusPictureViewItemWH)
            let url = pictureURLs!.first!
            if let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(url.absoluteString) {
                size = image.size
                size = CGSize(width: size.width * UIScreen.mainScreen().scale, height: size.height * UIScreen.mainScreen().scale)
            }

            if size.width < 40 {
                size.width = 40
            }

            let screenWith = UIScreen.mainScreen().bounds.width

            if size.width > screenWith * 0.5 {
                size.width = screenWith * 0.5
            }

            layout.itemSize = size
            return size
        }

        layout.minimumInteritemSpacing = DFStatusPictureViewCellMargin
        layout.minimumLineSpacing = DFStatusPictureViewCellMargin

        var column = DFStatusPictureViewMaxColumn

        if count == 2 || count == 4 {
            column = 2
        }

        let row = (count + column - 1) / column

        let width = CGFloat(column) * DFStatusPictureViewItemWH + (CGFloat(column) - 1) * DFStatusPictureViewCellMargin

        let height = CGFloat(row) * DFStatusPictureViewItemWH + (CGFloat(row) - 1) * DFStatusPictureViewCellMargin

        return CGSize(width: width, height: height)
    }
    
    private var layout = UICollectionViewFlowLayout()

    required init?(coder aDecoder: NSCoder) {
        fatalError()
    }

    init() {
        super.init(frame: CGRectZero,collectionViewLayout: layout)
        self.dataSource = self
        self.delegate = self
        backgroundColor = UIColor.clearColor()
        self.registerClass(DFStatusPictureViewCell.self, forCellWithReuseIdentifier: ReuseIdentifier)
    }

}

extension DFStatusPictureView: UICollectionViewDataSource,UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureURLs?.count ?? 0
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! DFStatusPictureViewCell

        cell.imageURL = pictureURLs![indexPath.item]
        return cell
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let browser = SDPhotoBrowser()
        browser.sourceImagesContainerView = collectionView
        browser.imageCount = pictureURLs?.count ?? 0
        browser.currentImageIndex = indexPath.item
        browser.delegate = self
        browser.show()
    }

}

extension DFStatusPictureView: SDPhotoBrowserDelegate {
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        let cell = cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) as! DFStatusPictureViewCell
        let image = cell.backImageView.image ?? UIImage(named: "avatar")
        return image
    }

    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        let thumbnaiURL = pictureURLs?[index].absoluteString
        let newURLString = thumbnaiURL?.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        return NSURL(string: newURLString!)
    }
}

class DFStatusPictureViewCell: UICollectionViewCell {

    var imageURL: NSURL? {
        didSet {
            backImageView.sd_setImageWithURL(imageURL!)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("")
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }

    private func prepareUI() {
        backImageView.contentMode = UIViewContentMode.ScaleAspectFill
        backImageView.clipsToBounds = true
        contentView.addSubview(backImageView)
        backImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
    }

    private lazy var backImageView:UIImageView = UIImageView()

}
